package com.hngy.xpq.sqlitedemo.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import androidx.annotation.Nullable;

import com.hngy.xpq.sqlitedemo.bean.Data;
import com.hngy.xpq.sqlitedemo.database.entity.DataOrder;

import java.util.ArrayList;
import java.util.List;

public class DataSql extends SQLiteOpenHelper {

    SQLiteDatabase sqLiteDatabase;

    public DataSql(@Nullable Context context) {
        super(context, DataOrder.DATABASE_DATA, null, DataOrder.DATABASE_INS);
        sqLiteDatabase = this.getWritableDatabase();
    }


    /**
     * Called when the database is created for the first time. This is where the
     * creation of tables and the initial population of the tables should happen.
     * 创建数据库
     * @param db The database.
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + DataOrder.DATABASE_TABLE + "("
                + DataOrder.NOTEPAD_ID + " integer primary key autoincrement,"
                + DataOrder.NOTEPAD_NAME + " VARCHAR(25),"
                + DataOrder.NOTEPAD_PASS + " VARCHAR(25))");
    }

    /**
     * Called when the database needs to be upgraded. The implementation
     * should use this method to drop tables, add tables, or do anything else it
     * needs to upgrade to the new schema version.
     *
     * <p>
     * The SQLite ALTER TABLE documentation can be found
     * <a href="http://sqlite.org/lang_altertable.html">here</a>. If you add new columns
     * you can use ALTER TABLE to insert them into a live table. If you rename or remove columns
     * you can use ALTER TABLE to rename the old table, then create the new table and then
     * populate the new table with the contents of the old table.
     * </p><p>
     * This method executes within a transaction.  If an exception is thrown, all changes
     * will automatically be rolled back.
     * </p>
     *
     * @param db         The database.
     * @param oldVersion The old database version.
     * @param newVersion The new database version.
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    /**
     * 增
     * @param d
     * @return
     */
    public boolean insert(Data d) {
        ContentValues values = new ContentValues();
        values.put(DataOrder.NOTEPAD_NAME, d.getName());
        values.put(DataOrder.NOTEPAD_PASS, d.getPass());
        return
                sqLiteDatabase.insert(DataOrder.DATABASE_TABLE, null, values) > 0;
    }

    /**
     * 删
     * @param id
     * @return
     */
    public boolean delete(int id) {
        String sql = DataOrder.NOTEPAD_ID + "=?";
        String[] va = new String[]{String.valueOf(id)};
        return
                sqLiteDatabase.delete(DataOrder.DATABASE_TABLE, sql, va) > 0;
    }

    /**
     * 改
     * @param d
     * @return
     */
    public boolean update(Data d) {
        ContentValues values = new ContentValues();
        values.put(DataOrder.NOTEPAD_NAME, d.getName());
        values.put(DataOrder.NOTEPAD_PASS, d.getPass());
        String sql = DataOrder.NOTEPAD_NAME + "=?";
        String[] id = new String[]{String.valueOf(d.getName())};
        return
                sqLiteDatabase.update(DataOrder.DATABASE_TABLE, values, sql, id) > 0;
    }

    /**
     * 查
     * @return
     */
    public List<Data> select() { // 全表遍历
        List<Data> list = new ArrayList<Data>();
        try {
            Cursor cursor = sqLiteDatabase.rawQuery("select * from " + DataOrder.DATABASE_TABLE,
                    null, null);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    Data d = new Data();
                    String id = cursor.getString(cursor.getColumnIndex(DataOrder.NOTEPAD_ID));
                    int ids = Integer.valueOf(id);
                    d.setId(ids);
                    d.setName(cursor.getString(cursor.getColumnIndex(DataOrder.NOTEPAD_NAME)));
                    d.setPass(cursor.getString(cursor.getColumnIndex(DataOrder.NOTEPAD_NAME)));
                    list.add(d);
                }
                cursor.close();
            } else {
                Log.i("DataSql-select", "获取Data的信息出现问题!!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public Data select(String name) { // 通过name获取id and pass
        Data d = null;
        try {
            Cursor cursor = sqLiteDatabase.rawQuery("select * from " + DataOrder.DATABASE_TABLE +
                    " where " + DataOrder.NOTEPAD_NAME + "=" + name,
                    null,null );
            if (cursor.moveToNext()){
                d = new Data();
                String id = cursor.getString(cursor.getColumnIndex(DataOrder.NOTEPAD_ID));
                int ids = Integer.valueOf(id);
                d.setId(ids);
                d.setName(cursor.getString(cursor.getColumnIndex(DataOrder.NOTEPAD_NAME)));
                d.setPass(cursor.getString(cursor.getColumnIndex(DataOrder.NOTEPAD_PASS)));
            } else {
                Log.i("DataSql-select", "连接异常!!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return d;
    }
}
